package org.jing.core.logger;

import org.jing.core.lang.BaseInitializer;
import org.jing.core.lang.JingException;
import org.jing.core.logger.itf.JingLoggerFactoryItf;
import org.jing.core.logger.sys.SingleLogger;

/**
 * Description: <br>
 *
 * @author bks <br>
 * @since 2023-09-19 <br>
 */
public class JingLoggerInitializer extends BaseInitializer<JingLoggerConfiguration> {
    @Override public void execute() {
        JingLoggerConfiguration config = getConfig();
        // 映射日志框架
        String frame = config.getFrame().toUpperCase();
        // 全局日志级别
        String globalLevel = config.getGlobalLevel();
        boolean localFlag = false;
        JingLoggerFactoryItf factory = null;
        try {
            switch (frame) {
                case "LOG4J":
                    factory = new org.jing.core.logger.log4j.LoggerFactory();
                    break;
                case "LOGBACK":
                    factory = new org.jing.core.logger.logback.LoggerFactory();
                    break;
                case "SLF4J":
                    factory = new org.jing.core.logger.slf4j.LoggerFactory();
                    break;
                default:
                    localFlag = true;
                    break;
            }
        }
        catch (Throwable t) {
            SingleLogger.err("failed to serialize factory by frame: {}", frame);
            SingleLogger.err("use default frame: local");
            SingleLogger.err(t);
            localFlag = true;
        }
        if (localFlag || !factory.isEnable()) {
            factory = new org.jing.core.logger.local.LoggerFactory();
        }
        try {
            // 日志框架初始化
            factory.init(config);
            // 设置全局级别
            factory.setGlobalLevel(globalLevel);
            JingLogger.setFactory(factory);
        }
        catch (Throwable t) {
            throw new JingException(t, "failed to initialize logger frame: {}", config.getFrame());
        }
    }
}
